package com.jin.core;

import com.jin.Exception.http.HttpException;
import com.jin.core.configuration.ExceptionCodeConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

//处理全局异常,捕获异常以后把异常处理为前端可视化的
//在代码里面抛出任何Exception那么就会被这个类所捕获
@ControllerAdvice
public class GlobalExceptionAdvice {


    @Autowired
    private ExceptionCodeConfiguration codeConfiguration;


    //对未知的异常进行处理
    @ExceptionHandler(value = Exception.class)
    //设置http的状态（500）
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public UnifyResponse handleException(HttpServletRequest req,Exception e){
        String requestUrl = req.getRequestURI();
        String method = req.getMethod();
        System.out.println(e);
        UnifyResponse unifyResponse = new UnifyResponse(9999,"服务器错误",method+" "+requestUrl);
        return unifyResponse;
    }


    //对已知的异常进行处理
    //根据方法的形参来决定监听那种类型的异常
    @ExceptionHandler(HttpException.class)
    public ResponseEntity<UnifyResponse> handleHttpException(HttpServletRequest req, HttpException e){
        String requestUrl = req.getRequestURI();
        String method = req.getMethod();
        HttpHeaders header = new HttpHeaders();
        //设置返回的响应体
        header.setContentType(MediaType.APPLICATION_JSON);
        UnifyResponse message = new UnifyResponse(e.getCode(),codeConfiguration.getCodes(e.getCode()),method+" "+requestUrl);
        //获取http的状态
        HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode());
        ResponseEntity<UnifyResponse> r = new ResponseEntity<>(message,header,httpStatus);
        return r;
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    //没有必要动态的去获取参数都是一样的
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public UnifyResponse handleBeanValidation(HttpServletRequest req,MethodArgumentNotValidException e){
        String requestUrl = req.getRequestURI();
        String method = req.getMethod();
        //获取message
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String messages = this.formatAllErrorMessage(errors);
        return new UnifyResponse(10001,messages,method+" "+requestUrl);

    }

    private String formatAllErrorMessage(List<ObjectError> errors){
        StringBuilder errorMsg = new StringBuilder();
        //error是集合中的一个元素
        errors.forEach(error->
            errorMsg.append(error.getDefaultMessage()).append(';')
        );
        return errorMsg.toString();
    }


    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public UnifyResponse handleConstraintException(HttpServletRequest req, ConstraintViolationException e){
        String requestUrl = req.getRequestURI();
        String method = req.getMethod();
        //直接通过e获取message
        String message = e.getMessage();
        return new UnifyResponse(10001,message,method+" "+requestUrl);
    }




}
